# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=cjson
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.7.12
pkgrel=2
pkgdesc="Ultralightweight JSON parser in ANSI C (mingw-w64)"
arch=(any)
url="https://github.com/DaveGamble/cJSON"
license=('MIT')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/DaveGamble/cJSON/archive/v${pkgver}.tar.gz"
        "001-fix-dll-dest.patch")
sha512sums=('d767b7261eff3a1a50ea46cc5573f9504f5734a891ea211ad348835bfb4b80acf7f744da2d34bb1fa270cd4d44576c21bc6f52c0604b7e6ffdeb61ecb396b376'
            'fce4def3f8f33afdd217ea334888c1b7cc20efe0e0dcc15de4639165d31066e27d5842555b2e7bbab3113c17de2b73f51a36b0cebc29fda13590eb134621d50f')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}

  patch -Np1 -i "${srcdir}"/001-fix-dll-dest.patch
}

build() {
  [[ -d ${srcdir}/build-${MINGW_CHOST} ]] && rm -rf ${srcdir}/build-${MINGW_CHOST}
  mkdir -p build-${MINGW_CHOST} && cd build-${MINGW_CHOST}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G Ninja \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DENABLE_CJSON_TEST=OFF \
    -DBUILD_SHARED_AND_STATIC_LIBS=ON \
    -DENABLE_CJSON_UTILS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd ${srcdir}/build-${MINGW_CHOST}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build . --target install

  for pcfile in  "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${MINGW_PREFIX}|\${prefix}|g" -i "${pcfile}"
    sed -i "1s|^|prefix=${MINGW_PREFIX}\\n|" "${pcfile}"
  done

  install -Dm644 ${srcdir}/${_realname}-${pkgver}/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
